#include <memory>
#include <iostream>
using std::cout;
using std::endl;
using std::unique_ptr;
using std::shared_ptr;

class Point
: public std::enable_shared_from_this<Point>
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {   cout << "Point(int,int)" << endl;    }

    ~Point()
    {   cout << "~Point()" << endl; }  

    //希望在类内部获取本对象的智能指针shared_ptr
    //正确用法：
    //1. 先继承自辅助类 enable_shared_from_this
    //2. 再调用其成员函数 shared_from_this()
    //Point * addPoint(Point & pt)
    shared_ptr<Point> addPoint(Point & pt)
    {
        _ix += pt._ix;
        _iy += pt._iy;
        //return shared_ptr<Point>(this);
        return shared_from_this();
    }

    void print() const 
    {
        cout << "(" << _ix
             << "," << _iy
             << ")" << endl;
    }

private:
    int _ix;
    int _iy;
};

void test0()
{
    //将一个原生的裸指针交给两个不同的智能指针进行托管
    //这会导致double free的问题
    Point * pt1 = new Point(1, 2);
    unique_ptr<Point> up1(pt1);
    unique_ptr<Point> up2(pt1);
}

void test1()
{
    Point * pt1 = new Point(1, 2);
    shared_ptr<Point> sp1(pt1);
    shared_ptr<Point> sp2(pt1);
}

void test2()
{
    shared_ptr<Point> sp1(new Point(1, 2));
    shared_ptr<Point> sp2(new Point(11, 12));

    sp2.reset(sp1.get());
}

void test3()
{
    shared_ptr<Point> sp1(new Point(1, 2));
    shared_ptr<Point> sp2(new Point(11, 12));
    
    shared_ptr<Point> sp3(sp1->addPoint(*sp2));
}


int main()
{
    /* test0(); */
    /* test1(); */
    /* test2(); */
    test3();
    return 0;
}

